import { createRouter, createWebHistory } from 'vue-router';
import App from '@/App.vue';
import Login from '@/pages/login/login.vue';
import Register from '@/pages/register/register.vue';
import { useUserStore } from '@/store/user';

const routes = [
  {
    path: '/',
    name: 'home',
    component: App,
    meta: { requiresAuth: true }
  },
  {
    path: '/login',
    name: 'login',
    component: Login
  },
  {
    path: '/register',
    name: 'register',
    component: Register
  }
];

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
});

// 登录验证
router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth) {
    const userStore = useUserStore();
    if (userStore.id) {
      next();
    } else {
      next('/login');
    }
  } else {
    next();
  }
});

export default router;
